<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">

      <el-breadcrumb-item><i class="el-icon-platform-eleme"></i> 用户管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入用户名称" v-model="query.userName">
            <el-button slot="append" icon="el-icon-search" @click="getUsers"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addUserDialogVisible=true">增加</el-button>
        </el-col>
      </el-row>
      <el-table
          :data="users"
          stripe
          style="width: 100%">
        <el-table-column
            prop="lname"
            label="名称"
            width="100">
        </el-table-column>
        <el-table-column
            prop="cname"
            label="别名"
            width="100">
        </el-table-column>
        <el-table-column
            prop="roles"
            label="拥有角色"
            width="100">
        </el-table-column>
        <el-table-column
            prop="email"
            label="邮箱"
            width="100">
        </el-table-column>
        <el-table-column
            prop="phone"
            label="电话"
            width="100">
        </el-table-column>
        <el-table-column
            prop="description"
            label="描述"
            width="100">
        </el-table-column>


        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
                size="mini"
                type="primary"
                @click="handleEdit(scope.row)">修改
            </el-button>
            <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.row)">删除
            </el-button>
            <el-button
                size="mini"
                type="warning"
                @click="handleUserRole(scope.row)">分配角色
            </el-button>
          </template>
        </el-table-column>

      </el-table>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="query.curPage"
          :page-sizes="[5, 10, 15, 30]"
          :page-size="query.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>

      <!--增加-->
      <el-dialog
          title="用户新增"
          :visible.sync="addUserDialogVisible"
          width="50%"
          @close="clearFrom">
        <el-form ref="addForm" :rules="rules" :model="user" label-width="50px">
          <el-form-item label="名称" prop="lname">
            <el-input v-model="user.lname"></el-input>
          </el-form-item>
          <el-form-item label="别名" prop="cname">
            <el-input v-model="user.cname"></el-input>
          </el-form-item>
          <el-form-item label="角色" prop="roles">
            <el-input v-model="user.roles"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="user.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="phone">
            <el-input v-model="user.phone"></el-input>
          </el-form-item>
          <el-form-item label="描述" prop="dname">
            <el-input v-model="user.description"></el-input>
          </el-form-item>
          <el-form-item label="标题" prop="tittle">
            <el-input v-model="user.tittle"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addUserDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveUser">确 定</el-button>
        </span>
      </el-dialog>

      <!--修改-->
      <el-dialog
          title="修改用户"
          :visible.sync="editUserDialogVisible"
          width="50%"
          @close="clearEditFrom">
        <!--校验规则  :rules="rules"   prop  表单域 model 字段，在使用 validate、resetFields 方法的情况下，该属性是必填的 -->
        <el-form ref="editForm" :rules="rules" :model="user" label-width="50px">
          <el-form-item label="名称" prop="lname">
            <el-input v-model="user.lname"></el-input>
          </el-form-item>
          <el-form-item label="别名" prop="cname">
            <el-input v-model="user.cname"></el-input>
          </el-form-item>
          <el-form-item label="角色" prop="roles">
            <el-input v-model="user.roles"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="user.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="phone">
            <el-input v-model="user.phone"></el-input>
          </el-form-item>
          <el-form-item label="描述" prop="dname">
            <el-input v-model="user.description"></el-input>
          </el-form-item>
          <el-form-item label="标题" prop="tittle">
            <el-input v-model="user.tittle"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editUserDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveEditRole">确 定</el-button>
        </span>
      </el-dialog>

      <!--角色分配-->
      <el-dialog
          title="角色分配"
          :visible.sync="userRoleDialogVisible"
          width="50%">
        <div style="text-align: center">
          <el-transfer
              style="text-align: left; display: inline-block"
              v-model="userRoles"
              :props="{
                 key: 'id',
                 label: 'cname'
               }"
              :titles="['待选角色列表', '已选角色列表']"
              :data="roless">
           <!-- <span slot-scope="{ option }">{{ option.key }} - {{ option.label }}</span>-->
          <!--  <el-button type="primary" icon="el-icon-arrow-up" slot="left-footer" size="small" circle style="text-align: center" @click="handleUp"></el-button>
            <el-button type="primary" icon="el-icon-arrow-down" slot="left-footer" circle size="small" style="text-align: center" @click="handleDown"></el-button>
           -->
            <!--<el-button type="primary" icon="el-icon-arrow-up" slot="right-footer" circle size="small" style="text-align: center" @click="handleUp"></el-button>
            <el-button type="primary" icon="el-icon-arrow-down" slot="right-footer" circle size="small" style="text-align: center" @click="handleDown"></el-button>
         --> </el-transfer>
        </div>

        <span slot="footer" class="dialog-footer">
          <el-button @click="userRoleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveRoles">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import {getData, postData, delData, putData} from "../../api/index";

export default {
  name: "Users",
  data() {
    return {

      roless:[],
      userId:-1,
      userRoles:[],



      userRoleDialogVisible:false,
      addUserDialogVisible: false,
      editUserDialogVisible: false,
      total: 0,
      users: [],
      user: {
        tittle: '',
        phone: '',
        email: '',
        lname: '',
        roles: '',
        cname: '',
        dname: '',
        description: ''
      },
      query: {
        userName: '',
        curPage: 1,
        pageSize: 5,
      },
      rules: {
        cname: [
          {required: true, message: '请输入角色名称', trigger: 'blur'},
          {min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur'}
        ],
      },

    }
  },
  methods: {
    /*分配角色*/
    async handleUserRole(userInfo) {
      const _this =this;
      _this.userId=userInfo.id;
      _this.userRoleDialogVisible = true;
      const res =await getData('sys/user/'+_this.userId)
      if (res.code === 20000) {
        _this.userRoles = res.data;
      }
    },
    async getRoles() {
      const _this = this;
      const res = await getData('sys/role/all')
      if (res.code === 20000) {
        _this.roless = res.data;
      }
    },
    /*  map(k=>   管道流  */
    async saveRoles() {
      const _this = this;
      const userRoles = _this.userRoles.map(k => {
        return {
          userid: _this.userId,
          roleid: k
        }
      })
      /*filter 过滤  include判断是否等于*/

      const roles = _this.roless.filter(k => {
        if (_this.userRoles.includes(k.id)) {
          return k
        }
      }).map(k => k.cname).join(',') || '-1'

      const res = await postData('sys/user/saveRoles/' + _this.userId + '/' + roles, userRoles)
      debugger
      if (res.code === 20000) {
        _this.$message.success(res.msg)
        _this.userRoleDialogVisible = false
      } else {
        _this.$message.error(res.msg)
      }
      debugger
    },




    /*修改*/
    async saveUser() {
      const _this = this;
      this.$refs.addForm.validate(async (valid) => {
        if (valid) {
          const res = await postData('sys/user', _this.user)
          if (res.code === 20000) {
            _this.$refs.addForm.resetFields();/*重置*/
            _this.$message.success(res.msg);
            await _this.getUsers();
            _this.addUserDialogVisible = false;
          } else {
            _this.$message.error(res.msg);
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      })
    },
    clearFrom() {
      this.user = {}
      this.$refs.addForm.resetFields();
    },

    /*修改*/
    handleEdit(userInfo) {
      /*深拷贝  创建新对象*/
      this.user = Object.assign(userInfo);/*   this.role= JSON.parse(JSON.stringify(roleInfo));   */
      this.editUserDialogVisible = true;
    },
    clearEditFrom() {
      this.user = {}
      this.$refs.editForm.resetFields();
    },
    saveEditRole() {
      const _this = this;
      this.$refs.editForm.validate(async (valid) => {
        if (valid) {
          const res = await putData('sys/user/' + _this.user.id, _this.user);
          if (res.code === 20000) {
            _this.$refs.editForm.resetFields();
            _this.$message.success(res.msg);
            await _this.getUsers();
            _this.editUserDialogVisible = false;
          } else {
            _this.$message.error(res.msg);
          }
        } else {
          return false;
        }
      });
    },

    /*删除*/
    async handleDelete(userInfo) {
      const _this = this;
      this.$confirm('您真的要删除' + userInfo.cname + '用户吗？ 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const res = await delData('sys/user/' + userInfo.id);
        if (res.code === 20000) {
          _this.$message.success(res.msg);
          await _this.getUsers();
        } else {
          _this.$message.error(res.msg);
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    /*获取*/
    async getUsers() {
      const _this = this
      const res = await getData('sys/user/list', _this.query)
      if (res.code === 20000) {
        _this.users = res.data.rows
        _this.total = res.data.total
      }
      console.log(res.data)
    },
    async addUserDiaulogVisible() {


    },
    handleSizeChange(val) {
      this.query.pageSize = val;
      this.getUsers()
    },
    handleCurrentChange(val) {
      this.query.curPage = val;
      this.getUsers()
    }
  },
  mounted() {
    this.getUsers()
    this.getRoles()
  },
}
</script>

<style scoped>
.transfer-footer {
  margin-left: 10px;
  padding: 6px 5px;
}
</style>